package com.hancher.gamelife2.saolei;

import com.hancher.common.androidutil.AsyncUtils;
import com.hancher.common.androidutil.ToastUtil;

import io.reactivex.rxjava3.disposables.Disposable;

/**
 * 作者 : Hancher ytu_shaoweijie@163.com <br/>
 * 时间 : 2023/5/20 19:56 <br/>
 * 描述 : 时间控制
 */
public class TimeControl {

    private static Disposable d = null;
    public static int TIME_COUNT = 100;
    public static int currentTimecount = 100;
    public static boolean isStart = false;
    public static SaoLeiView saoLeiView = null;

    public static void prepare() {
        TimeControl.isStart = false;
        currentTimecount = TIME_COUNT;
    }

    public static void start(SaoLeiView view) {
        //正在游戏
        if (isStart) {
            return;
        }
        currentTimecount = TIME_COUNT;
        isStart = true;
        saoLeiView = view;
        if (d != null && !d.isDisposed()) {
            d.dispose();
            d = null;
        }
        d = AsyncUtils.runCountdown(0L, (long) currentTimecount, 0L, 1000L,
                aLong -> {
                    //周期回调
                    if (!isStart) {
                        stop();
                        return;
                    }
                    currentTimecount -= 1L;
                    saoLeiView.invalidate();
                }, () -> {
                    ToastUtil.showErr("时间到，挑战失败，可继续游戏");
//                    stop();
                });
    }

    public static void stop() {
        if (d != null && !d.isDisposed()) {
            d.dispose();
            d = null;
        }
        isStart = false;
        saoLeiView = null;
    }
}
